import { queryPageApi, sportTrainDiaryAddApi } from "../../api/clockIn";
import tools from "../../tools/tools";
import store from "../../utils/store";

Page({
  data: {
    active: 1, // 默认选中“训练”对应的 TabBar 项，索引从 0 开始
    isReadOnly: false,
    formData: {
      trainDate: tools.formatDate(new Date()),  // 默认是今天
      studentId: store.state.studentId,
      coachId: store.state.coachId,
      content: '',
      remark: '',
      createUserId: store.state.studentId,
      createUserName: store.state.baseData?.studentName
    }
  },
  handleInput(e) {
    const key = e.currentTarget.dataset.key; // 获取data-key标记的字段名（content/remark）
    const value = e.detail; // 获取输入框的当前值
    // 动态更新formData对应的字段（微信小程序对象属性更新语法）
    this.setData({
      [`formData.${key}`]: value
    });
  },
  onLoad(options) {
    console.log(options, 'options')
    if(options.type == 1) {
      // 详情
      this.setData({
        isReadOnly: true  // 禁用表单
      })
      this.getDetail(options.date)
    }
  },
  // 提交
  onSubmit() {
    const { formData } = this.data
    const {content, remark} = formData
    console.log(content, remark)

    // 1. 表单校验
    if (!this.data.formData.trainDate) {
      wx.showToast({ title: '请选择训练日期', icon: 'none', duration: 1500 });
      return;
    }

    if (!content.trim()) {
      wx.showToast({ title: '请输入训练内容', icon: 'none', duration: 1500 });
      return;
    }

    if (content.trim().length > 500) {
      wx.showToast({ title: '训练内容最多输入500字', icon: 'none', duration: 1500 });
      return;
    }

    if (remark.trim().length > 300) {
      wx.showToast({ title: '备注最多输入300字', icon: 'none', duration: 1500 });
      return;
    }

    wx.showLoading({
      title: '提交中请稍等~',
      success: async () => {
        try {
          const sportRes = await sportTrainDiaryAddApi(this.data.formData)
          console.log(sportRes)
          if(sportRes.code == 0) {
          wx.showToast({ title: '提交成功', icon: 'success', duration: 1500 });
          } else {
            throw new Error(sportRes.msg)
          }
          wx.navigateBack({ delta: 1 });
          wx.hideLoading()
        } catch(err) {
          console.log(err)
          wx.hideLoading()
          wx.showToast({ title: '提交失败', icon: 'success', duration: 1500 });
        } 
      }
    })
  },
  // 获取详情数据
  async getDetail(date) {
    this.setData({
      date
    })
    const signRes = await queryPageApi({
      trainDate: date,
      studentId: store.state.studentId
    })
    if (signRes.code == 0) {
      const signList = signRes.data.list[0]
      console.log(signList, 'signList')
      this.setData({
        formData: signList
      })
    }
  },
  onChange(event) {
    // TabBar 切换事件，event.detail 为选中项的名称
    this.setData({
      active: event.detail
    });
    // 可根据不同的 TabBar 项，跳转不同页面或执行对应逻辑
    switch (event.detail) {
      case 0:
        // 假设“照片”对应页面路径
        wx.switchTab({
          url: "/pages/photo/photo"
        });
        break;
      case 1:
        // 当前“训练”页面，可做对应逻辑
        break;
      case 2:
        // 假设“日历”对应页面路径
        wx.switchTab({
          url: "/pages/calendar/calendar"
        });
        break;
      case 3:
        // 假设“成就”对应页面路径
        wx.switchTab({
          url: "/pages/achievement/achievement"
        });
        break;
      case 4:
        // 假设“我的”对应页面路径
        wx.switchTab({
          url: "/pages/mine/mine"
        });
        break;
      default:
        break;
    }
  }
});